package com.kaifamiao.iptoaddress;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
public class Demo {
    @GetMapping("/getIp")
    public Map<String, Object> getIp(HttpServletRequest request) {

        String remoteAddr = request.getRemoteAddr();
        // 如果使用了代理，如Nginx, Apache等，需从以下header中获取真实IP
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");
        String ip = (forwarded != null) ? forwarded.split(",")[0] : (realIp != null) ? realIp : remoteAddr;



        //获取IP地址后，格式化输出

        Map<String, Object> response = new HashMap<>();
        response.put("code", "200");
        response.put("status", "success");

        Map<String, Object> data = IpUtil.getIpRegion(ip);
        data.put("ip", ip);
        response.put("data", data);



        return response;
    }
}
